/**
 * 上午11:47:40
 */
package com.hsnn.medstgmini.base.std.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.std.dao.StdCompdrugprofileDao;
import com.hsnn.medstgmini.base.std.model.HospLevel;
import com.hsnn.medstgmini.base.std.model.StdCompdrugprofile;
import com.hsnn.medstgmini.base.std.model.StdCompdrugprofileLog;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;

/**
 * @author hsnn
 *
 */
@Repository
public class StdCompdrugprofileDaoImpl implements StdCompdrugprofileDao {

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@Autowired
	private HibernateSqlUtil dao;
	private Session getSession() {
		Session session = sessionFactory.getCurrentSession();
		if (null == session) {
			session = sessionFactory.openSession();
		}
		return session;
	}
	
	
	@Override
	public List<StdCompdrugprofile> getStdCompdrugprofileByName(String name) {
		Query query = getSession().createQuery("from StdCompdrugprofile where profileName='"+name+"'");
		@SuppressWarnings("unchecked")
		List<StdCompdrugprofile> list= query.list();
		return list;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination getStdCompdrugprofileList(Pagination page) {
		String compId = page.getConditions().get("compId");
		String prodId = page.getConditions().get("prodId");
			
		Query query = getSession().createQuery("from StdCompdrugprofile where compId='"+compId+"' and compProdId='"+prodId+"' order by updDatetime desc ");
		Query queryCount = getSession().createQuery("select count(*) from StdCompdrugprofile where compId='"+compId+"' and compProdId='"+prodId+"' ");
		
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		List<StdCompdrugprofile> list= query.list();
		Long records = (Long) queryCount.uniqueResult();
		page.setRecords(records.longValue());
		for (StdCompdrugprofile sc:list){
			sc.setProfileStarttimeStr(DateUtil.date(sc.getProfileStarttime()));
			sc.setProfileEndtimeStr(DateUtil.date(sc.getProfileEndtime()));
		}
		page.setRows(list);
		page.setSuccess(true);
		return page;
	}

	/**
	 * 获取药品资质信息
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Object> getStdCompdrugprofileLogList(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		
		Map<String, String> conditions = page.getConditions();
		String startDate =  conditions.get("startDate");
		String endDate =  conditions.get("endDate");
		
		// 查询总记录数
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) ")
		.append(" from std_compdrugprofile_log scl LEFT JOIN sys_user su on su.id = scl.upd_user  ")
		.append(" where scl.compprofile_id = :compprofileId ");
	
		StringBuffer sql = new StringBuffer()
		.append(" select scl.log_id logId, scl.profile_code profileCode, ")
		.append(" scl.profile_name profileName, ")
		.append(" scl.profile_starttime profileStarttime, ")
		.append(" scl.profile_endtime profileEndtime, ")
		.append(" scl.profile_pic_addr profilePicAddr, ")
		.append(" scl.status, ")
		.append(" scl.remarks, ")
		.append(" DATE_FORMAT(scl.upd_datetime,'%Y-%m-%d %H:%i:%S') updDatetime, ")
		.append(" scl.detail ,")
		.append(" su.name ")
		.append(" from std_compdrugprofile_log scl LEFT JOIN sys_user su on su.id = scl.upd_user  ")
		.append(" where scl.compprofile_id=:compprofileId   ");
		
		if (StringUtils.isNotBlank(startDate)) {
			sql.append(" and  DATE_FORMAT(scl.upd_datetime,'%Y-%m-%d') >= :startDate ");
			sb.append(" and  DATE_FORMAT(scl.upd_datetime,'%Y-%m-%d') >= :startDate ");
		}
		if (StringUtils.isNotBlank(endDate)) {
			sql.append(" and  DATE_FORMAT(scl.upd_datetime,'%Y-%m-%d') <= :endDate ");	
			sb.append(" and  DATE_FORMAT(scl.upd_datetime,'%Y-%m-%d') <= :endDate ");
		}
		sql.append(" order by scl.upd_datetime desc");
		
		SQLQuery queryCount = session.createSQLQuery(sb.toString());
		queryCount.setString("compprofileId",conditions.get("compprofileId"));
		
		SQLQuery query = session.createSQLQuery(sql.toString());
		query.setString("compprofileId",conditions.get("compprofileId"));
		if (StringUtils.isNotBlank(startDate)) {
			queryCount.setDate("startDate", ParseDate.fromShortFormat(startDate.trim()));
			query.setDate("startDate", ParseDate.fromShortFormat(startDate.trim()));
		}
		if (StringUtils.isNotBlank(endDate)) {
			queryCount.setDate("endDate", ParseDate.fromShortFormat(endDate.trim()));
			query.setDate("endDate", ParseDate.fromShortFormat(endDate.trim()));
		}
		
		Long total = Long.valueOf(queryCount.uniqueResult().toString());
		page.setRecords(total);
		query.setFirstResult((page.getPage()-1)*page.getMaxResults());
		query.setMaxResults(page.getMaxResults());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}
	
	/**
	 * @category 查询维护日志详情
	 * @date 2015年9月28日
	 * @param compprofileId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> getDrugProfileLogDetail(String logId) {
		String sql = " SELECT a.log_id logId,a.status, a.compprofile_id compprofileId, a.comp_id compId, a.comp_prod_id compProdId, a.profile_code profileCode, a.profile_name profileName, c.first_level_indi_name profileType, c.first_level_indi_name firstLevelIndiName, DATE_FORMAT(a.profile_starttime,'%Y-%m-%d') profileStarttime, DATE_FORMAT(a.profile_endtime,'%Y-%m-%d') profileEndtime, a.profile_pic_addr profilePicAddr, a.profile_pic_shortcut_addr profilePicShortcutAddr, a.remarks remark, DATE_FORMAT(a.upd_datetime,'%Y-%m-%d %T') updDatetime, d.name updUser FROM std_compdrugprofile_log a JOIN ( SELECT a.compprofile_id, a.upd_datetime FROM std_compdrugprofile_log a WHERE a.log_id = :logId ) b ON a.compprofile_id = b.compprofile_id AND a.upd_datetime <= b.upd_datetime LEFT JOIN dic_entprod_profile c ON a.profile_type = c.dic_entprod_profile_id LEFT JOIN sys_user d ON a.upd_user = d.id ORDER BY a.upd_datetime DESC LIMIT 2";
		Map<String,String> params = new HashMap<String,String>();
		/*Session session = sessionFactory.getCurrentSession();
		SQLQuery query = session.createSQLQuery(sql);
		query.setString("logId", logId);*/
		params.put("logId", logId);
		List<Map<String,Object>> list = (List<Map<String,Object>>) dao.getSqlMapList(sql.toString(), params);
		if(list!=null&&list.size()>0){
			for(int i = 0;i<list.size();i++){
				list.get(i).put("firstLevelIndiName", HospLevel.getName(list.get(i).get("firstLevelIndiName")==null?"":list.get(i).get("firstLevelIndiName").toString()));
			}
		}
		/*query.setMaxResults(2);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();*/
		return list;
	}
	
	/**
	 * @category 保存药品资质日志信息
	 * @author 韩守松
	 * @date   2015年10月26日
	 * @param  @param stdCompdrugprofileLog
	 * @param  @return
	 */
	public boolean saveLog(StdCompdrugprofileLog stdCompdrugprofileLog){
		writeLog(stdCompdrugprofileLog);
		return true;
	}

	/**
	 * 写日志
	 * @category 
	 * @Auther 徐国鹏
	 * @date 2015年9月21日 上午9:41:22
	 * @param stdCompinfo
	 * @return void
	 */
	public void writeLog(StdCompdrugprofileLog stdCompdrugprofileLog){
		Session session = getSession();
		// ----begin	
        StringBuffer detail = new StringBuffer();
		StringBuffer sb = new StringBuffer()
		.append("  select profile_code,profile_name,profile_type,profile_pic_addr,profile_pic_shortcut_addr,remarks,status  ")
		.append(" from std_compdrugprofile where compprofile_id =  :compprofileId ")
		.append(" union all ")
		.append(" select t.* from (select profile_code,profile_name,profile_type,profile_pic_addr,profile_pic_shortcut_addr,remarks,status ")
		.append("  from std_compdrugprofile_log where compprofile_id = :compprofileId  order by upd_datetime desc limit 1 ) t");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("compprofileId", stdCompdrugprofileLog.getCompprofileId());
		List<?> list = dao.getSqlList(sb.toString(), params);
		
		String[] colunm ={"资质编号","资质名称","资质图片","备注","状态"};
		if(list.size()==1){
			Object[] obj =(Object[]) list.get(0);
			obj[4] = obj[4]==null?"":"1".equals(obj[4].toString())?"启用":"停用";
			for(int i = 0;i<obj.length;i++){
				detail.append(";").append(colunm[i]).append(":").append(obj[i]==null?"":obj[i].toString());
			}
			detail.delete(0, 1);
		}else{
			Object[] obj1 =(Object[]) list.get(0);//修改后
			Object[] obj2 =(Object[]) list.get(1);//修改前
			obj1[4] = obj1[4]==null?"":"1".equals(obj1[4].toString())?"启用":"停用";
			obj2[4] = obj2[4]==null?"":"1".equals(obj2[4].toString())?"启用":"停用";
			for(int i = 0;i<obj1.length;i++){
				if(!(obj1[i]==null?"":obj1[i].toString()).equals(obj2[i]==null?"":obj2[i].toString())){
					detail.append(";").append(colunm[i]).append(":").append(obj2[i]==null?"":obj2[i].toString()).append(",").append(obj1[i]==null?"":obj1[i].toString());
				}
				
			}
			detail.delete(0, 1);
		}
		// ----end
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into std_compdrugprofile_log(compprofile_id,comp_id,comp_prod_id,profile_code,profile_name,profile_type,profile_starttime,profile_endtime,profile_pic_addr,profile_pic_shortcut_addr,status, ")
			.append(" remarks,upd_user,upd_datetime,audit_status,audit_datetime,audit_remark,audit_user,detail ")
			.append(" ) select ")
		    .append(" UUID(),t.compprofile_id,t.comp_id,t.comp_prod_id,t.profile_code,t.profile_name,t.profile_type,t.profile_starttime,t.profile_endtime,t.profile_pic_addr,t.profile_pic_shortcut_addr,t.status,t.remarks,t.upd_datetime,t.upd_user, ")
		    .append(" t.audit_status,t.audit_datetime,t.audit_remark,t.audit_user,:detail from std_compdrugprofile t where t.compprofile_id= :compprofileId ");
		Query query=session.createSQLQuery(sql.toString());
		query.setString("compprofileId",stdCompdrugprofileLog.getCompprofileId());
		query.setString("detail",detail.toString());
		query.executeUpdate();
		session.flush();
		
	}
}
